/**
 * @Created by zhuly8 zhuly8@yusys.com.cn on 2019-8-5 09:59:16.
 * @updated by
 * @description 应用系统管理
 */
define(['custom/widgets/js/yufpAgentSelect.js',
	'custom/widgets/js/YufpOrgTree.js',
	'custom/widgets/js/yufpUploadTable.js'],
	function (require, exports) {
		/**
		 * 页面加载完成时触发
		 * @param hashCode 路由ID
		 * @param data 传递数据对象
		 * @param cite 页面站点信息
		 */
		exports.ready = function (hashCode, data, cite) {
			yufp.lookup.reg('PROXY_FLAG');
			yufp.custom.vue({
				el: cite.el,
				data: function () {
					var _this_ = this;
					return {
						tbHeight:'100%',						
						searchformdata: {},
						selVisible: false,
						addFnButton: !yufp.session.checkCtrl('addFn'),
						updateFnButton: !yufp.session.checkCtrl('updateFn'),
						deleteFnButton: !yufp.session.checkCtrl('deleteFn'),
						importFnButton: !yufp.session.checkCtrl('importFn'),
						exportFnButton: !yufp.session.checkCtrl('exportFn'),
						dataUrl: 'api/use/plats/apps/queryWftAppList',
						upLoadUrl: yufp.service.getUrl({ url: "api/file/provider/uploadfile" }),
						sysDataUrl: '',
						saveBtnShow: true,
						cancelBtnShow: true,
						formdata: {},
						remarkFormData: {},
						isReadOnly: false,
						saveDisabled: false,
						async: false,
						param: { UNITID: '0000', LEVELUNIT: '1' },
						height: yufp.frame.size().height,
						dialogVisible: false,
						viewTitleArrry: ['应用系统新增', '应用系统修改', '应用系统详情'],
						viewTitle: '',
						propTableData: [],
						serverIdData: [],//调度引擎的列表
						agentName: "",
						addFlag: true,
						upLoadDialogVisible: false,
						appUploadDatas: [],
						refTemp: [],
						isAppImport: false,
						upLoadDataformdata: {},
						appCodeOptions: [],
						importMethod: "",
						exportTitle: "",
						importTypeName: "",
						importTypeOptions: [{ key: "P", value: "平台" }, { key: "A", value: "应用系统" }],
						initFilesParams: {
							condition: JSON.stringify({
								busNo: ''
							})
						},
						baseParam: { condition: { userId: yufp.session.userCode } },
						objectTabVisible: false,
						objDataUrl: "api/use/plats/serverdeploy/getAgtModuleList",
						queryObjFields: [{ placeholder: '集群代理代码', field: 'serverId', type: 'input' },
						{ placeholder: '服务名称', field: 'serverName', type: 'input' }],
						queryObjButtons: [
							{
								label: '搜索', op: 'submit', type: 'primary', click: function (model, valid) {
									_this_.$refs.refObjUsedTable.remoteData({ condition: model });
								}
							},
							{
								label: '确认', op: 'submit', type: 'primary', click: function () {
									let selectDatas = _this_.$refs.refObjUsedTable.selections; //当前确认选择
									let hadsel = _this_.propTableData || []; //已选
									if (selectDatas && selectDatas.length > 0) {
										var sbarr = [];
										selectDatas.forEach(item => {
											let falg = false;
											hadsel.forEach(self => {
												if (item.serverId == self.agentCode && 　item.serverName 　== 　self.serverName　) {
													falg = true;
													return;
												}
											})
											if (!falg) {
												/* 													obj.agentId = data[i].serverId;
																									obj.srvPort = data[i].srvPort;
																									obj.agentCode = data[i].serverId;
																									
																									obj.agentName = data[i].serverName;
																									obj.serverName = data[i].serverName; */


												var obj = {
													'agentId': item.serverId,
													'srvPort': item.srvPort,
													'agentCode': item.serverId,
													'agentName': item.serverName,
													'serverName': item.serverName,
													'remark': '',
												};

												sbarr.push(obj);
											}

										});
										_this_.propTableData = _this_.propTableData.concat(sbarr);
										_this_.$refs.refObjUsedTable.selections.splice(0);
										_this_.objectTabVisible = false;
									} else {
										_this_.$message({ message: "请选择一条记录!", type: "warning" });
										return;
									}
								}
							}
						]



					};
				},
				methods: {
					addFile: function () {
						// var paramObj = _this.searchFormdata;
						// paramObj.alarmClass = paramCode;
						// _this.$refs.refTable.remoteData({ condition: paramObj });
						this.objectTabVisible = true;
					},
					deleteFile: function () {
						var _this = this;
						var newData = [];
						var delDatas = _this.$refs.refAgentPropTable.selections;
						var allchecked = _this.propTableData || [];
						if (delDatas && delDatas.length > 0) {
							allchecked.forEach(item => {
								let flag = false;
								delDatas.forEach(self => {
									if (item.agentId == self.agentId && item.serverName == self.serverName) {
										flag = true;
									}
								});
								if (!flag) {
									newData.push(item);
								}
							});
							_this.propTableData = newData;
						} else {
							_this.$message({ message: "请选择一条记录!", type: "warning" });
							return;
						}

					},
					reloadData: function () {
						var _this = this;
						var param = { condition: JSON.stringify(_this.searchformdata) };
						_this.$refs.refTable.remoteData(param);
					},

					/**
					 * 取消
					 */
					cancelFn: function () {
						var _this = this;
						_this.clearAllFn();
						_this.dialogVisible = false;
					},
					/**
					 * 保存
					 */
					saveFn: function () {
						var _this = this;
						var model = {};
						var validate = false;
						_this.$refs.refForm.validate(function (valid) {
							validate = valid;
						});
						if (!validate) {
							return;
						}

						_this.saveDisabled = true;
						var paramObj = _this.$refs.refForm.formdata;
						paramObj.wftAgtList = _this.propTableData;
						paramObj.remark = _this.$refs.remarkRefForm.formdata.remark;
						let url = "";
						if (_this.addFlag) {
							url = 'api/use/plats/apps/add';
						} else {
							url = 'api/use/plats/apps/update';
						}

						yufp.service.request({
							method: 'POST',
							url: url,
							data: paramObj,
							callback: function (code, message, response) {
								if (response.code != 0) {
									_this.$message({ message: response.message, type: "warning" });

								} else {
									_this.$refs.refTable.remoteData();
									_this.$message('操作成功');
									_this.dialogVisible = false;
								}
								_this.saveDisabled = false;

							}
						});

					},
					/**
					 * 控制保存按钮、xdialog、表单的状态
					 * @param viewType 表单类型
					 * @param editable 可编辑,默认false
					 */
					switchStatus: function (viewType, editable) {
						var _this = this;
						_this.viewType = viewType;
						_this.dialogVisible = true;
						_this.saveBtnShow = editable;
						_this.cancelBtnShow = editable;
					},
					/**
					 * 新增
					 */
					addFn: function () {
						var _this = this;
						_this.dialogVisible = true;
						_this.viewTitle = _this.viewTitleArrry[0];
						_this.addFlag = true;
						_this.saveDisabled = false;
						_this.$nextTick(function () {
							_this.viewTitle = _this.viewTitleArrry[0];
							_this.clearAllFn();
						});
					},

					clearAllFn: function () {
						var _this = this;
						_this.$refs.refForm.resetFields();
						_this.$refs.refForm.resetFields();
						_this.$refs.remarkRefForm.resetFields();
						_this.agentName = "";
						_this.isReadOnly = false;
						//_this.formdata.agent = '';
						_this.propTableData.splice(0);


					},

					/**
					 * 修改
					 */
					modifyFn: function () {
						var _this = this;
						if (_this.$refs.refTable.selections.length != 1) {
							_this.$message({ message: '请先选择一条记录', type: 'warning', duration: 6000 });
							return;
						}
						_this.viewTitle = _this.viewTitleArrry[1];
						_this.dialogVisible = true;
						_this.addFlag = false;
						_this.saveDisabled = false;
						_this.$nextTick(function () {
							_this.clearAllFn();
							if (_this.$refs.refTable.selections[0].wftAgtList != null)
								for (let j = 0; j < _this.$refs.refTable.selections[0].wftAgtList.length; j++) {
									_this.propTableData.push(_this.$refs.refTable.selections[0].wftAgtList[j]);
								}
							_this.formdata.appCode = _this.$refs.refTable.selections[0].appCode;
							_this.formdata.appName = _this.$refs.refTable.selections[0].appName;
							_this.formdata.serverId = _this.$refs.refTable.selections[0].serverId;
							_this.agentName = _this.$refs.refTable.selections[0].serverName;
							_this.remarkFormData.remark = _this.$refs.refTable.selections[0].remark;
							_this.isReadOnly = true;

						})
					},

					viewFn: function (obj) {

						var _this = this;

						_this.viewTitle = _this.viewTitleArrry[2];
						_this.dialogVisible = true;
						_this.addFlag = false;
						_this.saveDisabled = true;
						_this.$nextTick(function () {
							_this.clearAllFn();
							for (let j = 0; j < obj.wftAgtList.length; j++) {
								_this.propTableData.push(obj.wftAgtList[j]);
							}
							_this.formdata.appCode = obj.appCode;
							_this.formdata.appName = obj.appName;
							_this.formdata.serverId = obj.serverId;
							_this.agentName = obj.serverName;
							_this.remarkFormData.remark = obj.remark;
							// _this.isReadOnly =true;

						})

					},



					selectAgentClickFn: function () {

						this.agentDialogVisible = true;
					},

					/**
					 * 选择代理
					 */
					selectAgentFn: function (data) {

						var _this = this;

						if (_this.propTableData.length > 0) {
							_this.propTableData.splice(0, _this.propTableData.length);
						}

						for (let i = 0; i < data.length; i++) {
							if (data[i].serverType === 'A') {
								var obj = {}
								obj.agentId = data[i].serverId;
								obj.srvPort = data[i].srvPort;
								obj.agentCode = data[i].serverId;

								obj.agentName = data[i].serverName;
								obj.serverName = data[i].serverName;
								_this.propTableData.push(obj);
							}

						}

					},

					initAgentData: function (data) {



						if (data.length > 0) {
							data.splice(0, data.length);
						}
						for (let i = 0; i < this.propTableData.length; i++) {
							data.push(_this.propTableData[i].agentId);
						}

					},
					/**
					 * 导入
					 */
					importFn: function () {
						var _this = this;
						_this.importTypeName = "导入类型"
						_this.upLoadDataformdata.importType = "";
						_this.upLoadDataformdata.appCode = "";
						_this.exportTitle = "导入操作";
						_this.importMethod = "I";
						_this.appUploadDatas.splice(0);
						_this.upLoadDialogVisible = true;


						// _this.$message({message: '功能开发中', type: 'warning',duration: 6000});
					},

					submitUpload: function () {
						//this.$refs.upload.submit();
					},

					/**
					 * check upload 操作
					 */
					checkUpload: function (file) {
						//alert(file);

						//检查类型和应用系统编号
						if (this.upLoadDataformdata.importType == null || this.upLoadDataformdata.importType == "") {
							this.$message.error('导入类型不能为空');
							return false;
						} else if (this.upLoadDataformdata.importType === 'A') {
							if (this.upLoadDataformdata.appCode == null || this.upLoadDataformdata.appCode === '') {
								this.$message.error('应用系统不能为空');
								return false;
							}
						}

						var isLt10M = file.size / 1024 / 1024 < 100;
						if (!isLt10M) {
							this.$message.error('上传文件大小不能超过 100MB!');
						}
						var index = file.name.lastIndexOf('.');
						var ext = file.name.substr(index + 1);

						var suffixValid = 'xml' === ext;
						if (!suffixValid) {
							this.$message.error('上传文件的格式必须为xml格式');
							return false;
						}
						return isLt10M && suffixValid;
					},

					successUpload: function (response, file, fileList) {

						const _this = this;
						const param = {};
						param.appCode = _this.upLoadDataformdata.appCode;
						param.importType = _this.upLoadDataformdata.importType;
						param.adminFileUploadInfo = response.data;

						yufp.service.request({
							method: 'POST',
							url: 'api/use/plats/apps/upLoadYuAppXml',
							data: param,
							callback: function (code, message, response) {
								if (response.code == 0) {
									//_this.$refs.refTable.remoteData();
									_this.reloadData();
									_this.upLoadDialogVisible = false;
									_this.$message('操作成功');
								} else {
									_this.$message({ message: response.message, type: "warning" });
								}
							}
						});


					},
					closeImpWindow: function () {
						this.upLoadDialogVisible = false;
					},

					exportViewFn: function () {
						var _this = this;
						_this.importTypeName = "导出类型"
						_this.upLoadDataformdata.importType = "";
						_this.upLoadDataformdata.appCode = "";
						_this.exportTitle = "导出操作";
						_this.importMethod = "E";
						_this.upLoadDialogVisible = true;

					},
					/**
					 * 导出
					 */
					exportFn: function () {

						/* if (_this.$refs.refTable.selections.length != 1) {
								 _this.$message({ message: '请先选择一条记录', type: 'warning',duration: 6000 });
								 return;
						 }*/

						//检查类型和应用系统编号
						if (this.upLoadDataformdata.importType == null || this.upLoadDataformdata.importType == "") {
							this.$message({ message: '导出类型不能为空', type: "warning" });
							return false;
						} else if (this.upLoadDataformdata.importType === 'A') {
							if (this.upLoadDataformdata.appCode == null || this.upLoadDataformdata.appCode === '') {
								this.$message({ message: '应用系统不能为空', type: "warning" });
								return false;
							}
						}

						yufp.util.download("api/use/plats/apps/downLoadYuAppXml?appCode=" + this.upLoadDataformdata.appCode);

					},
					/**
					 * 删除
					 */
					deleteFN: function () {
						var _this = this;
						var selections = _this.$refs.refTable.selections;
						if (selections.length != 1) {
							_this.$message({ message: '请先选择一条记录', type: 'warning', duration: 6000 });
							return;
						}
						_this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
							confirmButtonText: '确定',
							cancelButtonText: '取消',
							type: 'warning', duration: 6000,
							center: true,
							callback: function (action) {
								if (action === 'confirm') {
									yufp.service.request({
										method: 'POST',
										url: 'api/use/plats/apps/delete',
										data: _this.$refs.refTable.selections[0],
										callback: function (code, message, response) {
											if (response.code == 0) {
												_this.$refs.refTable.remoteData();
												_this.$message('操作成功');
											} else {
												_this.$message(response.message);
											}
										}
									});
								}
							}
						});
					},
					/**
					 * 新增参数
					 */
					propAddFn: function () {
						var _this = this;
						var obj;
						obj.paramCode = ' ';
						obj.paramName = ' ';
						obj.paramValue = ' ';
						_this.propTableData.push(obj);
					},
					/**
					 * 删除参数
					 */
					propDeleteFN: function () {
						var _this = this;
						var selections = _this.$refs.refPropTable.selections;
						if (selections.length < 1) {
							_this.$message({ message: '请先选择一条记录', type: 'warning', duration: 6000 });
							return;
						}
						var index = _this.$refs.refPropTable.data.indexOf(selections[0]);
						_this.propTableData.splice(index, 1);
					},


					changeImportType: function (objValue) {
						this.upLoadDataformdata.appCode = "";
						if (objValue === 'A') {
							this.isAppImport = true;
							this.queryAppOptions();
						} else {
							this.isAppImport = false;
						}

					},
					queryAppOptions: function () {
						var _this = this;
						_this.appCodeOptions.splice(0);
						yufp.service.request({
							url: backend.useService + '/plats/apps/getWftAppList',
							method: 'get',
							callback: function (code, message, response) {
								response.data.forEach(item => {
									var obj = {};
									obj.key = item.appCode;
									obj.value = item.appName;
									_this.appCodeOptions.push(obj);
								})
							}
						});
					},
					getServerIdData: function () { //查询调度引擎列表
						var _this = this;
						yufp.service.request({
							url: backend.useService + '/plats/serverdeploy/getCoreModuleList',
							method: 'get',
							callback: function (code, message, response) {
								console.log('list', response);
								if (response && response.code == '0') {
									var datalist = response.data || [];
									var listarr = [];
									datalist.forEach(item => {

										var obj = {};
										obj.key = item.serverId;
										obj.value = item.serverName;
										listarr.push(obj);
									})
									_this.serverIdData = listarr || [];
								} else {
									_this.$message({ message: response.message, type: 'warning', duration: 6000 });
								}
							}
						});
					}
				},
				mounted: function () {
					var _this = this;
					this.getServerIdData();
					
					_this.$nextTick(function(){
							var tableBox = _this.$refs.tableBox;
							let a = tableBox.getBoundingClientRect().top + 28;
							var theight = `calc(100vh - ${a}px - 64px)`;
							_this.tbHeight = theight;		
					});
				}
			});
		};
	});